//package com.alex.insistence.web.wechat;
//
//import java.text.MessageFormat;
//import java.util.Date;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//import org.apache.commons.io.IOUtils;
//import org.jeecgframework.core.util.ApplicationContextUtil;
//import org.jeecgframework.p3.core.utils.common.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.RequestMapping;
//
//import com.alex.insistence.rest.common.CardExceptionCode;
//import com.github.binarywang.wxpay.bean.WxPayOrderNotifyResponse;
//import com.github.binarywang.wxpay.bean.result.WxPayOrderNotifyResult;
//import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
//import com.gomore.cards.hd.HdBalanceService;
//import com.gomore.cards.hd.HdGiftCardService;
//import com.gomore.cards.rest.coupon.RsCoupon;
//import com.gomore.cards.rest.giftcard.hd.impl.RsHdGiftCardServiceImpl;
//import com.gomore.cards.rest.util.ServiceUtil;
//import com.gomore.cards.web.activity.ActivityService;
//import com.gomore.cards.web.cgform.activity.entity.CardActivityEntity;
//import com.gomore.cards.web.cgform.activity.service.CardActivityServiceI;
//import com.gomore.cards.web.cgform.card.entity.CardEntity;
//import com.gomore.cards.web.cgform.card.entity.CardStates;
//import com.gomore.cards.web.cgform.card.service.CardServiceI;
//import com.gomore.cards.web.cgform.cardhst.entity.CardActions;
//import com.gomore.cards.web.cgform.cardhst.entity.CardsCardHstEntity;
//import com.gomore.cards.web.cgform.cardhst.service.CardsCardHstServiceI;
//import com.gomore.cards.web.cgform.coupon.entity.CouponBuyOrderEntity;
//import com.gomore.cards.web.cgform.coupon.entity.CouponBuyOrderState;
//import com.gomore.cards.web.cgform.coupon.service.CouponBuyOrderServiceI;
//import com.gomore.cards.web.cgform.giftorder.entity.CardsGiftOrderEntity;
//import com.gomore.cards.web.cgform.giftorder.entity.CardsGiftOrderStates;
//import com.gomore.cards.web.cgform.giftorder.service.CardsGiftOrderServiceI;
//import com.gomore.cards.web.cgform.recharge.entity.CardsRechargeEntity;
//import com.gomore.cards.web.cgform.recharge.entity.CardsRechargeState;
//import com.gomore.cards.web.cgform.recharge.service.CardsRechargeServiceI;
//import com.gomore.hdcard.bean.Account;
//import com.gomore.hdcard.bean.DepositRequest;
//import com.gomore.hdcard.bean.DepositResponse;
//import com.gomore.hdcard.bean.OperateContext;
//import com.gomore.hdcard.bean.Operator;
//import com.gomore.hdcard.bean.RsDepositRequest;
//import com.gomore.hdcard.precard.RechargeService;
//import com.gomore.jeecg.common.ServiceException;
//import com.gomore.wechat.app.account.entity.WxAppAccountEntity;
//import com.gomore.wechat.app.account.service.WxAppAccountServiceI;
//import com.gomore.wechat.app.config.WxAppContext;
//
//import cn.binarywang.wx.miniapp.api.WxMaServiceEx;
//
///**
// * 微信支付
// * 
// * @author Debenson
// * @since 0.1
// */
//@Controller
//@RequestMapping(value = "wxPaymentController")
//public class WxPaymentController {
//  private static final Logger logger = LoggerFactory.getLogger(WxPaymentController.class);
//
//  @Autowired
//  private WxMaServiceEx wxAppService;
//  @Autowired
//  private CardsRechargeServiceI rechargeService;
//  @Autowired
//  private CardsGiftOrderServiceI giftOrderService;
//  @Autowired
//  private CardServiceI cardService;
//  @Autowired
//  private CardsCardHstServiceI cardHstService;
//  @Autowired
//  private CardActivityServiceI activityService;
//
//  @Autowired
//  private CouponBuyOrderServiceI couponBuyService;
//
//  @Resource
//  private ActivityService hdActivityService;
//
//  @Autowired
//  HdGiftCardService giftCardService;
//
//  @Autowired
//  WxAppAccountServiceI wxAppAccountService;
//
//  /**
//   * 微信通知支付结果的回调地址，notify_url
//   *
//   * @param request
//   * @param response
//   */
//  @RequestMapping(value = "payCallback")
//  public void payCallback(HttpServletRequest request, HttpServletResponse response)
//      throws Exception {
//    String xmlData = IOUtils.toString(request.getInputStream());
//    if (logger.isInfoEnabled()) {
//      logger.info("收到微信支付回调, 数据={}", xmlData);
//    }
//
//    if (StringUtils.isBlank(xmlData)) {
//      response.getWriter().write(WxPayOrderNotifyResponse.fail("no data"));
//      return;
//    }
//
//    WxPayOrderNotifyResult payResult = WxPayOrderNotifyResult.fromXML(xmlData);
//    WxAppContext.setAppId(payResult.getAppid());
//
//    try {
//      if (CardsRechargeEntity.class.getSimpleName().equals(payResult.getAttach())) {
//        processImprestOrder(payResult);
//      } else if (CardsGiftOrderEntity.class.getSimpleName().equals(payResult.getAttach())) {
//        processGiftOrder(payResult);
//      } else if (CouponBuyOrderEntity.class.getSimpleName().equals(payResult.getAttach())) {
//        processCouponOrder(payResult);
//      } else if (RsHdGiftCardServiceImpl.class.getSimpleName().equals(payResult.getAttach())) {
//        processHdGiftCardOrder(payResult);
//      }
//      response.getWriter().write(WxPayOrderNotifyResponse.success("ok"));
//    } catch (Exception e) {
//      logger.error("处理通知失败: ", e);
//      response.getWriter().write(WxPayOrderNotifyResponse.fail(e.getMessage()));
//    }
//  }
//
//  /**
//   * @param payResult
//   * @throws Exception
//   */
//  private void processHdGiftCardOrder(WxPayOrderNotifyResult payResult) throws Exception {
//    CardsGiftOrderEntity bill = giftOrderService.getByBillNumber(payResult.getOutTradeNo());
//    if (bill == null) {
//      throw new Exception("找不到指定的礼品卡订单，单号=" + payResult.getOutTradeNo());
//    }
//    if (!CardsGiftOrderStates.INIT.equals(bill.getState())) {
//      // 如果已经处理过，直接返回
//      return;
//    }
//
//    try {
//      payResult.checkResult((WxPayServiceImpl) wxAppService.getWxAppPayService());
//    } catch (Exception e) {
//      bill.setState(CardsGiftOrderStates.PAY_FAILED);
//      bill.setPayFailedMsg(e.getMessage());
//      giftOrderService.saveOrUpdate(bill);
//      throw e;
//    }
//
//    bill.setState(CardsGiftOrderStates.PAYED);
//    bill.setPayFlowNo(payResult.getTransactionId());
//    bill.setPayTime(new Date());
//    giftOrderService.saveOrUpdate(bill);
//
//  }
//
//  /**
//   * 处理购买券订单
//   * 
//   * @param payResult
//   */
//  private void processCouponOrder(WxPayOrderNotifyResult payResult) throws Exception {
//    CouponBuyOrderEntity bill = couponBuyService.findUniqueByProperty(CouponBuyOrderEntity.class,
//        "billNumber", payResult.getOutTradeNo());
//    if (bill == null) {
//      throw new Exception("找不到指定的充值订单，单号=" + payResult.getOutTradeNo());
//    }
//
//    if (!CouponBuyOrderState.INIT.equals(bill.getState())) {
//      return;
//    }
//
//    try {
//      payResult.checkResult((WxPayServiceImpl) wxAppService.getWxAppPayService());
//    } catch (Exception e) {
//      bill.setState(CouponBuyOrderState.PAY_FAILED);
//      bill.setPayFailedMsg(e.getMessage());
//      rechargeService.saveOrUpdate(bill);
//      throw e;
//    }
//
//    // 保存订单状态
//    bill.setState(CouponBuyOrderState.PAYED);
//    bill.setPayFlowNo(payResult.getTransactionId());
//    bill.setPayTime(new Date());
//
//    // 领券
//    try {
//      RsCoupon coupon = hdActivityService.buy(bill);
//      // 记录券码
//      bill.setCouponCode(coupon.getCode());
//    } catch (Exception e) {
//      logger.error("领券失败，券活动id=" + bill.getActivityId() + " 原因:" + e.getMessage());
//    }
//    couponBuyService.saveOrUpdate(bill);
//  }
//
//  /**
//   * 处理储值充值单
//   * 
//   * @param payResult
//   * @throws Exception
//   */
//  private void processImprestOrder(WxPayOrderNotifyResult payResult) throws Exception {
//    CardsRechargeEntity bill = rechargeService.getByBillNumber(payResult.getOutTradeNo());
//    if (bill == null) {
//      throw new Exception("找不到指定的充值订单，单号=" + payResult.getOutTradeNo());
//    }
//
//    if (!CardsRechargeState.INIT.equals(bill.getState())) {
//      return;
//    }
//
//    try {
//      payResult.checkResult((WxPayServiceImpl) wxAppService.getWxAppPayService());
//    } catch (Exception e) {
//      bill.setState(CardsRechargeState.PAY_FAILED);
//      bill.setPayFailedMsg(e.getMessage());
//      rechargeService.saveOrUpdate(bill);
//      throw e;
//    }
//
//    // 保存订单状态
//    bill.setState(CardsRechargeState.PAYED);
//    bill.setPayFlowNo(payResult.getTransactionId());
//    bill.setPayTime(new Date());
//    rechargeService.saveOrUpdate(bill);
//
//    // 完成海鼎订单，如果出现异常，将通过job不断处理
//    try {
//      if (ServiceUtil.isHdImpl()) {
//
//        WxAppAccountEntity acct = wxAppAccountService.getAccountByAppId(bill.getWxaAppId());
//        if (acct == null) {
//          throw new ServiceException("未查找到AppId为:" + bill.getWxaAppId() + "的小程序");
//        }
//        if (ServiceUtil.isHdCard(acct.getCardType())) {
//          recharge(bill);
//        } else {
//          HdBalanceService hdService = ApplicationContextUtil.getBean(HdBalanceService.class);
//          hdService.rechargeConfirm(bill.getBillNumber());
//          // 完成订单
//          bill.setState(CardsRechargeState.FINISHED);
//          rechargeService.saveOrUpdate(bill);
//        }
//      }
//    } catch (Exception e) {
//      logger.error("确认订单失败，将通过job尝试", e);
//    }
//  }
//
//  /**
//   * 调用hdcard的充值接口
//   * 
//   * @param bill
//   */
//  private void recharge(CardsRechargeEntity bill) {
//
//    RechargeService hdRechargeService = ApplicationContextUtil.getBean(RechargeService.class);
//    RsDepositRequest rsDepositRequest = new RsDepositRequest();
//    OperateContext ctx = new OperateContext();
//    ctx.setStore(bill.getStoreId());
//    ctx.setTime(new Date());
//    ctx.setOperator(new Operator("", bill.getHdMbrId(), bill.getUserName()));
//    ctx.setTerminalId(bill.getStoreId());
//    rsDepositRequest.setOperCtx(ctx);
//    DepositRequest request = new DepositRequest();
//    request.setAccount(new Account(bill.getAccountType(), bill.getAccountId()));
//    request.setPayTotal(bill.getPayAmount());
//    request.setTotal(bill.getAmount());
//    request.setTranId(bill.getBillNumber());
//    request.setTranType("cash");
//    request.setTranTime(new Date());
//    request.setXid(bill.getId());
//    rsDepositRequest.setRequest(request);
//
//    try {
//      DepositResponse resp = hdRechargeService.recharge(rsDepositRequest);
//      if (resp != null && resp.getCardNum() != null) {
//        bill.setState(CardsRechargeState.FINISHED);
//        rechargeService.saveOrUpdate(bill);
//      } else {
//        logger.info("储值充值失败");
//      }
//    } catch (Exception e) {
//      e.printStackTrace();
//      logger.info("储值充值失败" + e.getMessage());
//    }
//  }
//
//  /**
//   * 处理礼品卡订单
//   * 
//   * @param payResult
//   * @throws Exception
//   */
//  private void processGiftOrder(WxPayOrderNotifyResult payResult) throws Exception {
//    CardsGiftOrderEntity bill = giftOrderService.getByBillNumber(payResult.getOutTradeNo());
//    if (bill == null) {
//      throw new Exception("找不到指定的礼品卡订单，单号=" + payResult.getOutTradeNo());
//    }
//    if (!CardsGiftOrderStates.INIT.equals(bill.getState())) {
//      // 如果已经处理过，直接返回
//      return;
//    }
//
//    try {
//      payResult.checkResult((WxPayServiceImpl) wxAppService.getWxAppPayService());
//    } catch (Exception e) {
//      bill.setState(CardsGiftOrderStates.PAY_FAILED);
//      bill.setPayFailedMsg(e.getMessage());
//      rechargeService.saveOrUpdate(bill);
//      throw e;
//    }
//
//    // 分配卡号
//    final CardEntity card = apply(bill);
//
//    // 生成卡历史
//    saveBuyCardHst(card, bill);
//
//    // 保存订单状态
//    bill.setState(CardsGiftOrderStates.PAYED);
//    bill.setPayFlowNo(payResult.getTransactionId());
//    bill.setPayTime(new Date());
//    bill.setCardNum(card.getCode());
//    bill.setCardName(card.getName());
//    rechargeService.saveOrUpdate(bill);
//  }
//
//  /**
//   * 保存卡流水
//   * 
//   * @param card
//   * @param order
//   * @throws Exception
//   */
//  private void saveBuyCardHst(CardEntity card, CardsGiftOrderEntity order) throws Exception {
//    CardsCardHstEntity hst = new CardsCardHstEntity();
//    hst.setCardNum(card.getCode());
//    hst.setCardType(card.getType());
//    hst.setAction(CardActions.BUY);
//    hst.setNewOpenId(card.getOpenId());
//    hst.setNewUnionId(card.getUnionId());
//    hst.setNewBalance(card.getBalance());
//    hst.setBizBill(order.getBillNumber());
//    hst.setCreateDate(new Date());
//    hst.setUpdateDate(new Date());
//    hst.setRemark(MessageFormat.format("由礼品卡订单{0}生成", order.getBillNumber()));
//    cardHstService.save(hst);
//  }
//
//  private CardEntity apply(CardsGiftOrderEntity bill) throws Exception {
//    CardActivityEntity activity = activityService.get(CardActivityEntity.class,
//        bill.getActivityId());
//    if (activity == null) {
//      throw new ServiceException(CardExceptionCode.cardActivityNotFound);
//    }
//
//    CardEntity card = new CardEntity();
//    card.setName(activity.getName());
//    card.setType(activity.getType());
//    card.setBeginDate(activity.getBeginTime());
//    card.setEndDate(activity.getEndTime());
//    card.setState(CardStates.USING);
//    card.setBackground(bill.getBackground());
//    card.setBalance(bill.getFaveValueAmount()); // 面额 当作初始余额
//    card.setFaceValueName(bill.getFaceValueName());
//    card.setActivityId(activity.getId());
//    card.setDescription(activity.getUseRuleDesc());
//    card.setWxCardId(activity.getCardId());
//    card.setOpenId(bill.getWxaOpenid());
//    card.setUnionId(bill.getUnionId());
//    card.setGreetings(bill.getGreetings());
//    card.setRemark(MessageFormat.format("由订单{0}生成", bill.getBillNumber()));
//    card.setCreateDate(new Date());
//    card.setUpdateDate(new Date());
//    card.setSysOrgCode(bill.getSysOrgCode());
//    cardService.save(card);
//
//    // 更新卡券活动已发数量
//    updateActivityDistCount(activity);
//    return card;
//  }
//
//  private void updateActivityDistCount(CardActivityEntity activity) throws Exception {
//    String hql = "update " + CardActivityEntity.class.getName()
//        + " set distCount = coalesce(distCount, 0) + 1 where id = ?";
//    activityService.executeHql(hql, activity.getId());
//  }
//
//}
